package com.zhou.base.components.bs.common.util;

import cn.hutool.core.util.StrUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class GuavaCacheUtil {

	/**
	 * @desction: 使用google guava缓存处理
	 */
	private static Cache<String, Object> cache;

	static {
		cache = CacheBuilder.newBuilder().maximumSize(10000)
				.initialCapacity(10)
				.removalListener(new RemovalListener<String, Object>() {
					@Override
					public void onRemoval(RemovalNotification<String, Object> rn) {
						if (log.isInfoEnabled()) {
							log.info("被移除缓存{}:{}", rn.getKey(), rn.getValue());
						}
					}
				}).build();
	}

	/**
	 * @desction: 获取缓存
	 */
	public static Object get(String key) {
		return StrUtil.isNotEmpty(key) ? cache.getIfPresent(key) : null;
	}

	/**
	 * @desction: 放入缓存
	 */
	public static void put(String key, Object value) {
		if (StrUtil.isNotEmpty(key) && value != null) {
			cache.put(key, value);
		}
	}

	/**
	 * @desction: 移除缓存
	 */
	public static void remove(String key) {
		if (StrUtil.isNotEmpty(key)) {
			cache.invalidate(key);
		}
	}

	/**
	 * @desction: 批量删除缓存
	 */
	public static void remove(List<String> keys) {
		if (keys != null && keys.size() > 0) {
			cache.invalidateAll(keys);
		}
	}
}
